package com.itheima.controller;

import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import com.itheima.controller.results.Code;
import com.itheima.controller.results.Result;
import com.itheima.domain.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    //查询单个
    @GetMapping("/{uuid}")
    public Result get(@PathVariable Integer uuid){
        User user = userService.get(uuid);
        if(user==null){
            return new Result(Code._ERROR);
        }
        return new Result(Code._OK,user);
    }
    //新增
    @PostMapping ()
    public Result save( User user){
        boolean flag = userService.save(user);
        return new Result(flag ? Code._OK:Code._ERROR);
    }
    //修改
    @PutMapping
    public Result update(User user){
        boolean flag =  userService.update(user);
        return new Result(flag ? Code._OK:Code._ERROR);
    }
    //删除
    @DeleteMapping("/{uuid}")
    public Result delete(@PathVariable Integer uuid){
        boolean flag = userService.delete(uuid);
        return new Result(flag ? Code._OK:Code._ERROR);
    }
    //分页查询
    @GetMapping("/{page}/{size}")
    public Result getAll(@PathVariable int page, @PathVariable int size){
        PageInfo<User> all = userService.getAll(page, size);
        if(all==null){
            return new Result(Code._ERROR);
        }
        return new Result(Code._OK,all);
    }
    //登录
    @PostMapping("/login")
        public Result login(String userNAME,String PASSWORD){
        User login = userService.login(userNAME, PASSWORD);
        if(login==null){
            return new Result(Code._ERROR,null,Code.MESSAGE_ERROR);
        }
        return new Result(Code._OK,login,Code.MESSAGE_OK);
    }

}
